package com.itheima.redbaby.activity;

import java.util.List;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.redbaby.BaseActivity;
import com.itheima.redbaby.GloableParams;
import com.itheima.redbaby.R;
import com.itheima.redbaby.bean.FavoriteProduct;
import com.itheima.redbaby.engine.UserEngine;
import com.itheima.redbaby.factory.DaoAndEngineFactory;
import com.itheima.redbaby.utils.ImageUtil;
import com.itheima.redbaby.utils.PromptManager;
/**
 * 收藏夹列表界面
 * @author Gaara
 *
 */
public class FavoritesListActivity extends BaseActivity implements OnClickListener {
	//收藏夹数量初始默认为0
	private int favoritesNum = 0;
	private List<FavoriteProduct> favoritesList;
	private FavoritesAdapter adapter;
	private ListView myfavorite_product_list;
	private TextView head_clean;
	private TextView head_account_center;
	private TextView head_back_text;
	private LinearLayout myfavorite_productlist_layout;
	private RelativeLayout myfavorite_empty;
	//是否在滑动加载数据.
	private boolean isLoading = false;
	//加载收藏夹第几页,默认从第一页开始
	private int page = 1;
	//每页需要显示的条目数量.
	private int pageNum = 6;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_favorite_activity);
		myInit();
	}
	/**
	 * 初始化资源
	 */
	private void myInit() {
		myfavorite_product_list = (ListView) findViewById(R.id.myfavorite_product_list);
		
		head_back_text = (TextView) findViewById(R.id.head_back_text);
		head_clean = (TextView) findViewById(R.id.head_clean);
		
		head_account_center = (TextView) findViewById(R.id.head_account_center);
		
		myfavorite_productlist_layout = (LinearLayout) findViewById(R.id.myfavorite_productlist_layout);
		myfavorite_empty = (RelativeLayout) findViewById(R.id.myfavorite_empty);
	}
	class FavoritesAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return favoritesList.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v;
			ViewHolder holder;
			if(convertView != null){
				v = convertView;
				holder = (ViewHolder) v.getTag();
			}else{
				holder = new ViewHolder();
				v = View.inflate(FavoritesListActivity.this, R.layout.my_favorite_listitem, null);
				holder.myfavorite_product_img = (ImageView) v.findViewById(R.id.myfavorite_product_img);
				holder.myfavorite_title_text = (TextView) v.findViewById(R.id.myfavorite_title_text);
				holder.myfavorite_addition_text = (TextView) v.findViewById(R.id.myfavorite_addition_text);
				holder.myfavorite_price_text = (TextView) v.findViewById(R.id.myfavorite_price_text);
				holder.myfavorite_deleteprice_text = (TextView) v.findViewById(R.id.myfavorite_deleteprice_text);
				holder.myfavorite_nostock_text = (TextView) v.findViewById(R.id.myfavorite_nostock_text);
				
				v.setTag(holder);
			}
			FavoriteProduct pro = favoritesList.get(position);
			//TODO gaara加载网络图片使用xUtils工具,待详细了解使用...
			ImageUtil.loadImageFromUrl(holder.myfavorite_product_img, pro.getPic());
			holder.myfavorite_title_text.setText(pro.getName());
			holder.myfavorite_price_text.setText("￥"+pro.getPrice());
			holder.myfavorite_deleteprice_text.setText("￥"+pro.getMarketprice());
			//删除线
			holder.myfavorite_deleteprice_text.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
			holder.myfavorite_deleteprice_text.getPaint().setAntiAlias(true);
			holder.myfavorite_nostock_text.setText("已有"+pro.getCommentcount()+"人评价");
			if(pro.getProductprom()!=null){
				holder.myfavorite_addition_text.setText(pro.getProductprom());
			}
			return v;
		}
		class ViewHolder{
			ImageView myfavorite_product_img;
			TextView myfavorite_title_text;
			TextView myfavorite_addition_text;
			TextView myfavorite_price_text;
			TextView myfavorite_deleteprice_text;
			TextView myfavorite_nostock_text;
		}
		
	}
	@Override
	protected void onResume() {
		//初始数据
		favoritesList = null;
		page = 1;
		prepareData(page, pageNum);
		super.onResume();
	}
	/**
	 * 后台分页查询
	 * @param page 第几页
	 * @param pageNum 每页加载数量
	 */
	private void prepareData(final int page,final int pageNum) {
		new MyHttpTask() {
			@Override
			protected void onPreExecute() {
				if(page == 1){
					PromptManager.showProgressDialog(FavoritesListActivity.this);
//					如果2秒之内没有服务器回应信息,关掉对话框.
					new Handler().postDelayed(new Runnable() {
						
						@Override
						public void run() {
							PromptManager.closeProgressDialog();
						}
					}, 2000);
				}
			}
			@Override
			protected Object doInBackground(Void... params) {
				//模拟分页加载,获取实现效果.
				SystemClock.sleep(1000);
				UserEngine userEngine = DaoAndEngineFactory.getImpl(UserEngine.class);
				return userEngine.getFavoritesList(page, pageNum);
			}
			@Override
			protected void onPostExecute(Object result) {
				if(page == 1){
					PromptManager.closeProgressDialog();
				}
				if(result != null){
					JSONObject json = (JSONObject) result;
					String response = json.getString("response");
					if(response.equals("favorites")){
						if(page == 1){
							//分页查询时不再重复的获取数量.
							favoritesNum = json.getIntValue("list_count");
							if(favoritesNum == 0){
								//收藏夹为空
								showEmptyState();
								return;
							}else{
								showListView();
							}
						}
						String text = json.getString("productlist");
						if(favoritesList == null){
							favoritesList = JSON.parseArray(text, FavoriteProduct.class);
						}else{
							favoritesList.addAll(JSON.parseArray(text, FavoriteProduct.class));
						}
						fillData();
					}else{
						PromptManager.showToast(FavoritesListActivity.this, "数据获取失败...");
					}
				}else{
					PromptManager.showToast(FavoritesListActivity.this, "服务器连接异常,请重试...");
					showEmptyState();
				}
			}
		}.executeHttp();
	}
	/**
	 * 展示listview页面的一些页面布局准备
	 */
	protected void showListView() {
		head_account_center.setVisibility(View.GONE);
		myfavorite_empty.setVisibility(View.GONE);
		head_clean.setVisibility(View.VISIBLE);
		head_back_text.setVisibility(View.VISIBLE);
		myfavorite_productlist_layout.setVisibility(View.VISIBLE);
		
		head_back_text.setOnClickListener(this);
		head_clean.setOnClickListener(this);
		head_account_center.setOnClickListener(null);
	}
	/**
	 * 展示空页面时的页面布局准备
	 */
	protected void showEmptyState() {
		head_account_center.setVisibility(View.VISIBLE);
		myfavorite_empty.setVisibility(View.VISIBLE);
		head_clean.setVisibility(View.GONE);
		head_back_text.setVisibility(View.GONE);
		myfavorite_productlist_layout.setVisibility(View.GONE);
		
		head_back_text.setOnClickListener(null);
		head_clean.setOnClickListener(null);
		head_account_center.setOnClickListener(this);
	}
	/**
	 * 更新listview
	 */
	private void fillData() {
		if(adapter == null){
			adapter = new FavoritesAdapter();
			setListener();
			myfavorite_product_list.setAdapter(adapter);
			return;
		}
		adapter.notifyDataSetChanged();
		isLoading = false;
	}
	/**
	 * 对listview设置滑动监听事件和条目点击事件.
	 */
	private void setListener() {
		myfavorite_product_list.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE://静止状态
					if(isLoading){
						PromptManager.showToast(FavoritesListActivity.this, "正在加载...");
						return;
					}
					//目前已知在320*480分辨率中,版画面可显示3个半条目.
					if(favoritesNum < 5){
						return;
					}
					int position = myfavorite_product_list.getLastVisiblePosition();
					if(page*pageNum >= favoritesNum && position == favoritesList.size()-1){
						PromptManager.showToast(FavoritesListActivity.this, "已经全部加载,亲...");
						//myfavorite_product_list.setOnScrollListener(null);
						return;
					}
					if(position == favoritesList.size()-1){
						PromptManager.showToast(FavoritesListActivity.this, "加载更多...");
						page ++;
						prepareData(page, pageNum);
						isLoading = true;
					}
					break;
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
		myfavorite_product_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//TODO gaara产品详情页面进行衔接.
				FavoriteProduct favoriteProduct = favoritesList.get(position);
				int ProductId = favoriteProduct.getId();
				Intent intent = new Intent(FavoritesListActivity.this, ProductDetailActivity.class);
				intent.putExtra("pId", ProductId);
				startActivity(intent);
			}
		});
	}
	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.head_back_text://返回
			finish();
			break;
		case R.id.head_account_center://账户中心
			//其实和返回一样.
			finish();
			break;
		case R.id.head_clean://清空
			cleanFavorites();
			break;
		}
	}
	/**
	 * 后台清空收藏夹
	 */
	private void cleanFavorites() {
		new MyHttpTask() {
			
			@Override
			protected void onPreExecute() {
				PromptManager.showProgressDialog(FavoritesListActivity.this);
//				如果2秒之内没有服务器回应信息,关掉对话框.
				new Handler().postDelayed(new Runnable() {
					
					@Override
					public void run() {
						PromptManager.closeProgressDialog();
					}
				}, 2000);
			};

			@Override
			protected void onPostExecute(Object result) {
				PromptManager.closeProgressDialog();
				if(result != null){
					String text = (String) result;
					if(text.equals("succeed")){
						PromptManager.showToast(FavoritesListActivity.this, "清除成功...");
						showEmptyState();
					}else{
						PromptManager.showToast(FavoritesListActivity.this, text);
					}
				}else{
					PromptManager.showToast(FavoritesListActivity.this, "服务器连接异常,请重试...");
				}
			}

			@Override
			protected Object doInBackground(Void... params) {
				//模拟链接延迟.
				SystemClock.sleep(500);
				UserEngine userEngine = DaoAndEngineFactory.getImpl(UserEngine.class);
				return userEngine.cleanFavorites();
			}
		}.executeHttp();
	}
}
